package com.scorekeeper.objects;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Parcel;

import com.scorekeeper.utils.DBProvider;

public final class Extensions 
	extends DBProvider 
	implements DBObject 
{
	public int _id;
	public String name;
	public String value;
	public int teamId;
	private CastType type;
	
	public Extensions(Context context) {
		super(context);
		this._id = -1;
	}
	
	@Override
	public ContentValues loadContentValues() {
		ContentValues cv = new ContentValues();
		
		cv.put("Name", this.name);
		cv.put("Value", this.value);
		cv.put("TeamId", this.teamId);
		cv.put("ExtType", this.type.toInt());
		
		return cv;
	}
	
	@Override
	public int describeContents() { return hashCode(); }
	
	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeLong(this._id);
		dest.writeString(this.name);
		dest.writeInt(type.toInt());
		dest.writeString(this.value.toString());
		dest.writeInt(this.teamId);
	}
	
	@Override
	public void loadFromParcel(Parcel loadFrom) {
		this._id = loadFrom.readInt();
		this.name = loadFrom.readString();
		this.type = CastType.lookup((int) loadFrom.readInt());
		this.value = loadFrom.readString();
		this.teamId = loadFrom.readInt();
	}
	
	@Override
	public boolean load(int id) {
		this._id = id;
		return load();
	}
	
	@Override
	public boolean load() {
		boolean rv = false;
		
		this.open();
		
		//ensure a valid id
		if (this._id != -1) {
			Cursor cur = this.select("SELECT * FROM EXT_VALUE WHERE Id = ?", new String[] { Integer.toString(this._id) });
			if (this.isValidCursor(cur)) {
				this._id = cur.getInt(0);
				this.name = cur.getString(1);
				this.value = cur.getString(2);
				this.teamId = cur.getInt(3);
				this.type = CastType.lookup(cur.getInt(4));
				
				rv = true;
			}
		}
		
		this.close();
		return rv;
	}

	@Override
	public void save() {
		this.open();
		
		if (this._id != -1) {
			//update
			this.update(Table.EXTENSION.Name(), loadContentValues(), "Id=?", new String[] { Integer.toString(this._id) } );
		} else {
			//insert
			this._id = (int) this.insert(Table.EXTENSION.Name(), loadContentValues());
		}
		
		this.close();
	}
	
	@Override
	public void delete() {
		//TODO:
	}
	
	public final static class ExtensionConstants {
		public final static String ROW ="ROW";
		public final static String STREAK = "Streak";
		public final static String LASTTEN = "Last10";
		public final static String SO = "S/O";
		public final static String AWAY = "AwayRec";
		public final static String HOME = "HomeRec";
		public final static String GA = "GA";
		public final static String GF = "GF";
		public final static String CLINCH = "Clinched";
	}
}
